class PlayScene extends eui.Component{
	private gameData:GameData

	/**当前被选中的卡 */
	private _curSelectedCard:BaseCard
	/**当前被选中的空格 */
	private _curPlace:CardPosition
	/**卡片拖动组件 */
	private dragCard:CardComponent
	private touchStartY:number
	private placaAble:boolean[][][]
    
	/**发动确认框 */
	private confirmPanel:eui.Component
	private txtConfirm:eui.Label
	private btnActCancel:eui.Button
	private btnActConfirm:eui.Button

	private btnTurnEnd:eui.Button
	private btnHandSwitch:eui.Button
	/**卡片详细框 */
	private cardDetail:CardDetail
	private fieldPanelP1:FieldPanel
	private fieldPanelP2:FieldPanel
	private fieldPanels:FieldPanel[]
	private handP1:eui.Component
	private handP2:eui.Component
	private lpP1:LifeBar
	private lpP2:LifeBar
	private lpBars:LifeBar[]
	private txtTurn:eui.Label
	private txtDistance:eui.Label
	private fieldP1:eui.Component
	private fieldP2:eui.Component
	private txtTips:eui.Label
	private basePanel:eui.Component

	/**当前是否正在显示武器手牌 */
	private _curShowingWeaponHands:boolean
	private _halfHeight:number

	public constructor(gd:GameData) {
		super()
		this.skinName = 'resource/eui_skins/scene/play.exml'
		this.gameData = gd
		this.once(eui.UIEvent.CREATION_COMPLETE, this.onComplete, this)	
		this.touchStartY = -1
		this._halfHeight = this.height/2
	}

	protected onComplete(e:any){
		const t = this
		t.gameData.addEventListener(PlayEvents.CPU_ACT_FINISH, t.onCpu, t)
		t.gameData.addEventListener(PlayEvents.PHRASE_CHANGED, t.onPhraseChanged, t)

		t.lpP1.LP = t.gameData.players[0].life
		t.lpP1.playerNum = 1
		t.lpP2.LP = t.gameData.players[1].life
		t.lpP2.playerNum = 2
		t.lpBars = [t.lpP1, t.lpP2]
		
		t.fieldPanelP1 = new FieldPanel(0, t.fieldP1, t.handP1)
		t.fieldPanelP2 = new FieldPanel(1, t.fieldP2, t.handP2)
		t.basePanel.addEventListener("touchBegin", t.globalClickHandler, t)
		t.fieldPanels = [t.fieldPanelP1, t.fieldPanelP2]

		t.fieldPanelP1.addHandCard(t.gameData.players[0].weapons)
		t._curShowingWeaponHands = true
		t.fieldPanelP2.addHandCard(t.gameData.players[1].hand)

		t.btnActConfirm.addEventListener("touchTap", t.onConfirmAct, t)
		t.btnActCancel.addEventListener("touchTap", t.onCancelAct, t)
		t.btnHandSwitch.addEventListener("touchTap", t.onHandSwitch, t)
		// t.turnEnd()
		t.refresh()
		t.lpBars[t.gameData.curRound].turnIn()
		t.onPhraseChanged()
		t.gameData.gameStart()
		// t.refresh()
	}

	protected globalClickHandler(e:egret.TouchEvent){
		const t = this
		if(t.gameData.phrase == GamePhrase.CONFIRM) return
		if(e.target instanceof CardComponent){
			const cardDisp = e.target as CardComponent
			const tmpc = cardDisp.card
			if(!tmpc.isFront && tmpc.player.index != t.gameData.userPlayerNum){
				return
			}
			t.onCardSelected({
				data:{
					card:cardDisp.card
				}
			})
			return
		}
		if(e.target.name.indexOf('cell') >= 0){
			const cell = e.target as eui.Component
			if(cell.numChildren >= 2){
				const cc = cell.getChildAt(1) as CardComponent
				const tmpc = cc.card
				if(!tmpc.isFront && tmpc.player.index != t.gameData.userPlayerNum){
					return
				}
				t.curSelectedCard = tmpc
				//点选武装卡时弹出发动攻击的确认提示
				if(tmpc.type == CardType.WEAPON && t.gameData.phrase == GamePhrase.WAIT){
					if(tmpc.player.actWeapon == 0) return
					t.gameData.phrase = GamePhrase.CONFIRM
					const cp = tmpc.curPlace
					const cell = t.fieldPanels[cp.f].places[cp.i][cp.j]
					t.showConfirmPanel(cp.f, cell)
				}
				return
			}
		}
		if(e.target == t.btnTurnEnd){
			t.onBtnTurnEndHandler()
		}
		if(t._curSelectedCard){
			t.curSelectedCard = null
		}
	}

	protected onCardSelected(e:any){
		const t = this
		if(t.gameData.phrase == GamePhrase.CONFIRM) return
		if(!e.data.card){
			t.curSelectedCard = null
			return
		}
		const card:BaseCard = e.data.card as BaseCard
		if(card != t._curSelectedCard) {
			t.curSelectedCard = card
		}

		//没有发动战术or护盾卡次数时点选了战术or护盾卡
		if(card.type == CardType.SKILL && card.player.actSkill == 0) return
		else if(card.type == CardType.SET_SHIELD && card.player.actShield == 0) return
		//非攻击阶段点选了反应型护盾卡
		if(card.type == CardType.ACT_SHIELD && t.gameData.phrase!=GamePhrase.DEF_JUDGE) return
		if(t.touchStartY==-1)t.touchStartY = t.handP1.localToGlobal(t.handP1.x, t.handP1.y).y

		const gp = t.gameData.phrase
		if(card.type == CardType.WEAPON && gp.indexOf("STANDBY")>=0){
			t.addEventListener("touchMove", t.onTouchMove, t)
			t.once(egret.TouchEvent.TOUCH_END, t.onWeaponTouchEnd, t)
		}
		else if(gp == GamePhrase.WAIT){
			t.addEventListener("touchMove", t.onTouchMove, t)
			t.once(egret.TouchEvent.TOUCH_END, t.onTouchEnd, t)
		}
	}

	protected async onTouchMove(e:egret.TouchEvent){
		const t = this
		if(!t._curSelectedCard)return
		if(!t.dragCard){
			if(e.stageY > t.touchStartY){
				return
			}
		}		
		if(!t.dragCard){
			const disp = t._curSelectedCard.display
			const drag = new CardComponent(t._curSelectedCard, false)			
			
			drag.visible = false
			drag.isThumb = true
			drag.isFront = true	
			t.dragCard = drag
			t.dragCard.x = e.stageX  - t.dragCard.width/2
			t.dragCard.y = e.stageY - t.dragCard.height/2	
			t.addChild(t.dragCard)
		
			setTimeout(function() {
				if(drag) drag.visible = true
				disp.dragged = true
			}, 100);
			
		}else{
			t.dragCard.x = e.stageX - t.dragCard.width/2
			t.dragCard.y = e.stageY - t.dragCard.height/2	
		}
		if(t.cardDetail.showPlace == 1 && e.stageY < t._halfHeight){
			t.cardDetail.y = 1050
		}else if(t.cardDetail.showPlace == -1 && e.stageY > t._halfHeight){
			t.cardDetail.y = 50 
		}
	}

	protected onTouchEnd(e:egret.TouchEvent){
		const t = this
		t.removeEventListener("touchMove", t.onTouchMove, t)
		const cell:eui.Component = e.target
		const cname:string = cell.name
		let fieldIdx:number = e.stageY > t._halfHeight?0:1
		let actConfirm:boolean = true
		let i:number
		let j:number
		if(cname.indexOf('cell') < 0){
			actConfirm = false
		}else{
			i = parseInt(cname[4]) 
			j = parseInt(cname[5])
			t._curPlace = {f:fieldIdx, i, j}
			if(!t.placaAble[fieldIdx][i][j]){
				actConfirm = false
			}
		}
		if(!actConfirm){
			t.onCancelAct(null)
		}else{
			//发动确认
			t.gameData.phrase = GamePhrase.CONFIRM
			if(t.dragCard){
				t.dragCard.x = 0
				t.dragCard.y = 0
				cell.addChild(t.dragCard)
			}
			t.showConfirmPanel(fieldIdx, cell)
		}
	}

	protected async onWeaponTouchEnd(e:egret.TouchEvent){
		const t = this
		t.removeEventListener("touchMove", t.onTouchMove, t)
		const cell:eui.Component = e.target
		const cname:string = cell.name
		/**是否设置武装卡 */
		let placeWeapon:boolean = true
		let i:number
		let j:number
		if(cname.indexOf('cell') < 0){
			placeWeapon = false
		}else{
			i = parseInt(cname[4])
			j = parseInt(cname[5])
			t._curPlace = {f:0, i, j}
			if(!t.placaAble[0][i][j]){
				placeWeapon = false
			}
		}
		if(t.dragCard && placeWeapon){
			const cmov:CardMoveData = t.gameData.putCard(t._curSelectedCard, t._curPlace)
			await t.fieldPanels[cmov.player].moveCard(cmov)
			
			t.dragCard.parent && t.dragCard.parent.removeChild(t.dragCard)
			t.dragCard = null
			t._curPlace = null	
		}
	
		t._curSelectedCard.display.dragged = false
		if(placeWeapon){
			t.curSelectedCard = null
		}
		// t.cardDetail.y = 50
	}

	private showConfirmPanel(fieldIdx:number, cell:eui.Component){
		const t = this
		if(!t._curSelectedCard)return 
		switch(t._curSelectedCard.type){
			case CardType.WEAPON:
				t.txtConfirm.text = `确认启动武装 ${t._curSelectedCard.name}`
				break
			case CardType.ACT_SHIELD:
				t.txtConfirm.text = `确认展开护盾 ${t._curSelectedCard.name}`
				break
			case CardType.SET_SHIELD:
				t.txtConfirm.text = `确认设置护盾 ${t._curSelectedCard.name}`
				break
			case CardType.SKILL:
				t.txtConfirm.text = `确认执行战术 ${t._curSelectedCard.name}`
				break
		}
		let tmpY:number = fieldIdx==0?0:cell.height
		const tmpP = cell.localToGlobal(cell.width/2, tmpY)
		t.confirmPanel.x = tmpP.x - t.confirmPanel.width/2
		const tmpRight = t.confirmPanel.x + t.confirmPanel.width
		if(tmpRight > t.width){
			t.confirmPanel.x -= (tmpRight - t.width + 20)
		}
		t.confirmPanel.y = tmpP.y - t.confirmPanel.height - 20 
		t.confirmPanel.visible = true
	}

	protected async onConfirmAct(e:any){
		const t = this
		if(t._curPlace){
			return
		}
		const card = t._curSelectedCard
		const cp = card.curPlace
		const cell = t.fieldPanels[cp.f].places[cp.i][cp.j]
		const cpn = cell.getChildAt(1) as CardComponent

		t.confirmPanel.visible = false
		if(t.dragCard){
			t.dragCard = null
			t._curPlace = null
		}
		t.curSelectedCard = null	
		
		switch(card.type){
			case CardType.WEAPON:
				await cpn.flip()
			case CardType.SKILL:
			case CardType.ACT_SHIELD:
				await t.gameData.cardHandler(card)
				await cpn.remove()
				cell.removeChild(cpn)
				break
			case CardType.SET_SHIELD:
				await t.gameData.cardHandler(card)
				break
		}
		t.refresh()
		t.gameData.phrase = GamePhrase.WAIT
		// t.turnEnd()
	}
	protected onCancelAct(e:any){
		//取消拖拽
		const t = this
		//有事件参数传入时为动作确认框点击取消按钮，重置到自由阶段
		if(e)t.gameData.phrase = GamePhrase.WAIT
		t.confirmPanel.visible = false
		if(t.dragCard){
			t.dragCard.parent && t.dragCard.parent.removeChild(t.dragCard)
			t.dragCard = null
			t._curPlace = null
			t._curSelectedCard.display.dragged = false
		}
		t.cardDetail.y = 50
	}

	protected async onHandSwitch(e:any=null){
		const t = this
		t.curSelectedCard = null
		if(t._curShowingWeaponHands){
			await t.fieldPanelP1.switchHand(t.gameData.players[0].hand)
		}else{
			await t.fieldPanelP1.switchHand(t.gameData.players[0].weapons)
		}
		t._curShowingWeaponHands = !t._curShowingWeaponHands
	}

	protected async onCpu(e:egret.Event){
		const t = this
		const data = e.data as CardMoveData
		if(data.toField){
			await t.fieldPanels[data.player].moveCard(data)
		}
	}

	protected onPhraseChanged(e:any=null){
		const t = this
		switch(t.gameData.phrase){
			case GamePhrase.STANDBY:
				t.txtTips.text = '选择武装卡放置到场上以开始游戏'
				t.btnTurnEnd.visible = false
				break
			case GamePhrase.STANDBY_FINISH:
				t.txtTips.text = '点击按钮开始对战'
				t.btnTurnEnd.visible = true
				t.btnTurnEnd.label = '开始游戏'
				break
			case GamePhrase.WAIT:
				t.txtTips.text = '选择要使用的卡片'
				break
		}
	}

	public refresh(){
		const t = this
		const gd = t.gameData
		t.txtTurn.text = `${gd.curTurn}`
		t.txtDistance.text = `${gd.curDistance}`
		t.fieldPanels[0].setActIconStatus(gd.players[0])
		t.fieldPanels[1].setActIconStatus(gd.players[1])
		t.lpP1.LP = t.gameData.players[0].life
		t.lpP2.LP = t.gameData.players[1].life
	}

	protected async turnEnd(e:any=null){
		const t = this
		t.gameData.turnEnd()
		t.cardDetail.visible = false
		t.fieldPanelP1.removeAllHighlight()
		t.fieldPanelP2.removeAllHighlight()
		await t.lpBars[1-t.gameData.curRound].turnOut()
		await t.lpBars[t.gameData.curRound].turnIn()
		t.refresh()	
	}

	protected onBtnTurnEndHandler(e:any=null){
		const t = this
		switch(t.gameData.phrase){
			case GamePhrase.STANDBY_FINISH:
				//开始游戏
				t.gameData.phrase = GamePhrase.WAIT
				t.btnTurnEnd.label = '回合结束'
				t.btnHandSwitch.visible = false
				if(t._curShowingWeaponHands){
					t.fieldPanelP1.switchHand(t.gameData.players[0].hand)
					t._curShowingWeaponHands = false
				}
				break
			case GamePhrase.WAIT:
				break
		}
	}

	protected set curSelectedCard(v:BaseCard){
		const t = this
		if(t._curSelectedCard == v) return
		t._curSelectedCard = v
		if(v){
			
			if(!v.curPlace){
				//已放置在场上的卡不显示高亮
				const emptyPlace = t.gameData.getEnablePlace(v)
				t.fieldPanelP1.highlightHand([v])
				t.fieldPanelP1.highlightPlace(emptyPlace[0])
				t.fieldPanelP2.highlightPlace(emptyPlace[1])	
				t.placaAble = emptyPlace
			}else{
				t.fieldPanelP1.removeAllHighlight()
				t.fieldPanelP2.removeAllHighlight()
				t.fieldPanels[v.curPlace.f].hightlightCell(v.curPlace.i, v.curPlace.j, true)
			}	
			t._curSelectedCard = v
			
			t.cardDetail.card = v
			t.cardDetail.y = 50
			t.cardDetail.visible = true

		}else{
			t.cardDetail.visible = false
			t.fieldPanelP1.removeAllHighlight()
			t.fieldPanelP2.removeAllHighlight()
		}
	}
	
}